package org.example.road.learn01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.AttributeKey;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.SystemPropertyUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.road.learn01.handler.EchoHandler;
import org.example.road.learn01.handler.ExceptionHandler;
import org.example.road.learn01.handler.PingHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;

@Slf4j
public class OutMemoryError2 {

    private static final Integer CONNECTIONS = 100;

    private static final Integer THREADS = Math.max(1, SystemPropertyUtil.getInt(
            "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

    public static AttributeKey<Integer> idAttr = AttributeKey.newInstance("clientId");

    public static void main(String[] args) {
        ThreadFactory threadFactory = new DefaultThreadFactory("clientthread");

        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup loopGroup = new NioEventLoopGroup(THREADS, threadFactory);
        bootstrap.group(loopGroup);
        bootstrap.channel(NioSocketChannel.class);
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // ch.pipeline().addLast(loggingHandler);
                ch.pipeline().addLast(new EchoHandler());
                ch.pipeline().addLast(new PingHandler(3));
                ch.pipeline().addLast(new ExceptionHandler());
            }
        });


        for (int i = 0; i < CONNECTIONS; i++) {
            try {
                final int clientId = i;
                final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080));
                channelFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            log.info("客户端{}连接成功", clientId);
                            future.channel().attr(idAttr).set(clientId);
                        }
                    }
                });
                final Channel channel = channelFuture.channel();
                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            final Integer clientId = future.channel().attr(idAttr).get();
                            log.info("连接{}优雅关闭资源", clientId);
                            future.channel().close();
                            // loopGroup.shutdownGracefully();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("main线程结束");
    }
}
